<template>
  <div class="leftCenterLine">
    <dv-loading style="color: aqua" v-if="loading">{{ $t('loading') }}</dv-loading>
    <div ref="app" class="echarts" v-else></div>
  </div>
</template>
<script>
import * as echarts from "echarts";
import { getWorkshopMonthList } from "@/api/index";
export default {
  data() {
    return {
      xdata: "",
      ydata1: [],
      ydata2: [],
      ydata3: [],
      ydata4: [],
      loading: false,
      screenWidth: document.body.clientWidth, //获取当前宽度并存储
      screenHeight: document.body.clientHeight, //获取当前高度并存储
      myChart: "", //存储init后生成的图表全部内容
    };
  },

  methods: {
    // 预处理数据，去除周末
    removeWeekends(data) {
      var filteredData = data.filter(function (item) {
        var date = new Date(item);
        var day = date.getDay(); // 0 表示周日，6 表示周六
        return day !== 0; // 保留周一到周五的数据
      });
      return filteredData;
    },
    //保留月日
    getMonthDay(dateString) {
      const date = new Date(dateString);
      if (isNaN(date.getTime())) {
        throw new Error("Invalid date string");
      }
      const month = date.getMonth() + 1; // getMonth() 从 0 开始计数
      const day = date.getDate();
      return `${month.toString().padStart(2, "0")}-${day
        .toString()
        .padStart(2, "0")}`;
    },
    //接口请求
    getrequests() {
      getWorkshopMonthList().then((res) => {
        if (res.code == 200) {
          this.loading = false;

          //处理x轴日期
          let dataX = res.data.map((item) => {
            return this.parseTime(item.classDay);
          });
          let dataX1 = this.removeWeekends(dataX);
          this.xdata = dataX1.map((item) => {
            return this.getMonthDay(item);
          });

          //去掉周末数据y轴
          let ydata = this.xdata.map((item1) => {
            let arr = res.data.filter(
              (item) => this.getMonthDay(item.classDay) == item1
            );
            return arr[0];
          });
          this.ydata1 = ydata.map((item) => {
            return Math.round(
              (item.onTime /
                (item.onTime + item.offTime + item.noTime + item.ngTime)) *
                100
            );
          });
          this.ydata2 = ydata.map((item) => {
            return Math.round(
              (item.offTime /
                (item.onTime + item.offTime + item.noTime + item.ngTime)) *
                100
            );
          });
          this.ydata3 = ydata.map((item) => {
            return Math.round(
              (item.noTime /
                (item.onTime + item.offTime + item.noTime + item.ngTime)) *
                100
            );
          });
          this.ydata4 = ydata.map((item) => {
            return Math.round(
              (item.ngTime /
                (item.onTime + item.offTime + item.noTime + item.ngTime)) *
                100
            );
          });
          this.$nextTick(() => {
            this.getdata();
          });
        }
      });
    },
    getdata() {
      var timer = null;
      let that = this;
      var myChart = echarts.init(this.$refs.app);
      this.myChart = myChart; //将init后的存储到myChart变量中
      var option;
      let dataX = this.xdata;
      option = {
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: [this.$t('page3.leftBox2.legend.utilization'), this.$t('page3.leftBox2.legend.idleRate'), this.$t('page3.leftBox2.legend.downtimeRate'), this.$t('page3.leftBox2.legend.failureRate')],
          textStyle: {
            color: "white", // 设置图例文字颜色
            fontSize: 12, // 设置图例文字字体大小
          },
          type: "scroll", // 设置为可滚动的图例
        },
        grid: {
          left: "1%",
          right: "5%",
          bottom: "4%",
          containLabel: true,
        },
        xAxis: {
          name: this.$t('page3.leftBox2.xAxis.date'),
          type: "category",
          boundaryGap: true,
          nameTextStyle: {
            color: "#a6cac9",
            fontSize: 10,
          },
          data: dataX,
          axisLabel: {
            textStyle: {
              color: "#a6cac9", // X轴字体颜色
              fontSize: 15, // X轴字体大小
            },
          },
        },
        yAxis: {
          name: this.$t('page3.leftBox2.yAxis.percentage'),
          type: "value",
          max: 100, //最大值
          min: 0, //最小值
          interval: 20, //间隔
          axisTick: {
            show: false,
          },
          nameTextStyle: {
            color: "#a6cac9",
            fontSize: 10,
          },
          axisLabel: {
            textStyle: {
              color: "#a6cac9",
              fontSize: 13,
            },
          },
        },
        series: [
          {
            name: this.$t('page3.leftBox2.legend.idleRate'),
            type: "bar",
            data: this.ydata2,
            label: {
              show: true,
              position: "top",
              color: "#8E99E4",
              fontSize: 11,
              formatter: "{c}" + "%",
            },
          },
          {
            name: this.$t('page3.leftBox2.legend.utilization'),
            type: "line",
            data: this.ydata1,
            lineStyle: {
              width: 4, // 设置线条宽度为3
            },
            label: {
              show: true,
              position: "top",
              color: "#8E99E4",
              fontSize: 14,
              formatter: "{c}" + "%",
            },
          },
          {
            name: this.$t('page3.leftBox2.legend.downtimeRate'),
            type: "bar",
            data: this.ydata3,
            label: {
              show: true,
              position: "top",
              color: "#8E99E4",
              fontSize: 11,
              formatter: "{c}" + "%",
            },
          },
          {
            name: this.$t('page3.leftBox2.legend.failureRate'),
            type: "bar",
            data: this.ydata4,
            label: {
              show: true,
              position: "top",
              color: "#8E99E4",
              fontSize: 11,
              formatter: "{c}" + "%",
            },
          },
        ],
        // 自动滚动
        dataZoom: [
          //滑动条
          {
            show: false, //是否显示滑动条
            type: "slider", // 这个 dataZoom 组件是 slider 型 dataZoom 组件
            startValue: 0, // 从头开始。
            endValue: 11, // 一次性展示5个。
          },
          {
            type: "slider", // 这里可以选择你需要的dataZoom类型
            start: 0, // 滑动条开始位置（百分比）
            end: 100, // 滑动条结束位置（百分比）
          },
        ],
      };
      // 使用刚指定的配置项和数据显示图表。
      timer = setInterval(function () {
        // 每次向后滚动一个，最后一个从头开始。
        if (option.dataZoom[0].endValue == dataX.length - 1) {
          option.dataZoom[0].endValue = 11;
          option.dataZoom[0].startValue = 0;
        } else {
          option.dataZoom[0].endValue = option.dataZoom[0].endValue + 1;
          option.dataZoom[0].startValue = option.dataZoom[0].startValue + 1;
        }
        myChart.setOption(option, true);
      }, 5000);

      window.addEventListener("resize", () => {
        //使用resize监听方法
        that.screenWidth = document.body.clientWidth; //给存储的变量screenWidth赋当前窗口的宽度
        window.screenWidth = that.screenWidth;
        that.screenHeight = document.body.clientHeight; //给存储的变量screenHeight赋当前窗口的高度
        window.screenHeight = that.screenHeight;
      });

      option && myChart.setOption(option);
    },
   
  },
  mounted() {
    this.getrequests();
    setInterval(() => {
      this.getrequests();
    }, 3600000);
  },
  watch: {
    screenWidth() {
      this.myChart.resize(); //当监听到变量screenWidth更新后调用myChart的resize()方法
    },
    screenHeight() {
      this.myChart.resize(); //当监听到变量screenHeight更新后调用myChart的resize()方法
    },
  },
};
</script>
<style scoped>
.echarts {
  width: 100%;
  height: 42vh;
}
</style>
